package org.bot.plugin.web.event;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 沧月
 * @create 0022 2023/9/22 13:28
 * @description <description class purpose>
 */

@Component
@EventName("批量设置值")
public class WebBatchSetValue implements Events {

    @Autowired
    WebSetValue webSetValue;

    @Override
    public Object exec(FlowNode note, DataStorage data) {
        String arg = note.getArg();
        JSONArray array = JSONArray.parseArray(arg);
        FlowNode flowNode = new FlowNode();
        Object values = data.get(note.getDataIndex());
        if (values == null) {
            return null;
        }
        if (!(values instanceof Map)) {
            return null;
        }

        Map mapValues = (Map) values;
        array.forEach(o -> {
            JSONObject _tmp = (JSONObject) o;
            Object value = mapValues.get(_tmp.get("key"));
            if (value == null) {
                value = "";
            }
            flowNode.setDriveWeb(note.getDriveWeb());
            flowNode.setArg(_tmp.getString("arg"));
            flowNode.setSelectorType(note.getSelectorType());
            flowNode.setStaticValue(value.toString());
            webSetValue.exec(flowNode, data);
        });
        return null;
    }
}
